# -*- coding: utf-8 -*-
"""
Created on Wed Nov 29 12:35:46 2017

@author: Luther
"""

import requests
from bs4 import BeautifulSoup
import pandas as pd

input_path = input("请输入输入文件路径：")
#input_path = "C:\Users\Luther\Desktop\Belt_Road\data\py\geo_py_input.xls"

add = pd.read_excel(input_path)
add.index = add.id
add = add.drop('id', axis=1)

province = []
city = []
district = []
count = 0
for i in range(len(add)):
    lat = add.lat.iloc[i]
    lng = add.lng.iloc[i]
    url = "http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location={:},{:}&output=xml&pois=1&ak=5mSNiWKjGK0FZtuL5yc09GRb4wHYDiNU".format(
        lat, lng)
    try:
        r = requests.get(url, timeout=120)
        r.raise_for_status
        soup = BeautifulSoup(r.text, 'lxml')
        if int(soup.status.string) == 0:
            province.append(soup.province.string)
            city.append(soup.city.string)
            district.append(soup.district.string)
        else:
            province.append(0)
            city.append(0)
            district.append(0)
    except:
        province.append(0)
        city.append(0)
        district.append(0)

    count = count + 1
    print("\r当前进度: {:.2f}%".format(count * 100 / len(add)), end="")

add['province'] = province
add['city'] = city
add['district'] = district
add.to_excel("D:\\r.xls")
output_path = input("请输入输出文件路径：")
#output_path = "C:\Users\Luther\Desktop\Belt_Road\data\py\geo_py_output.xls"
add.to_excel(output_path)
